package com.itheima.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.Result;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LogInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从session域中获取用户信息
        Object user = request.getSession().getAttribute("user");
        //判断是否登录成功,如果登录失败就响应错误信息并拦截
        if (user == null) {
            //响应错误信息
            ObjectMapper objectMapper = new ObjectMapper();
            response.setContentType("application/json;charset=utf-8");
            objectMapper.writeValue(response.getWriter(), new Result(false, "还没有登录,无权访问"));
            //拦截
            return false;
        }
        //如果登录成功就放行
        return true;
    }
}
